//格式化时间
function dateFtt(fmt, date) { //author: meizz
    var o = {
        "M+": date.getMonth() + 1,                 //月份
        "d+": date.getDate(),                    //日
        "h+": date.getHours(),                   //小时
        "m+": date.getMinutes(),                 //分
        "s+": date.getSeconds(),                 //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function formatSubscribeTime(cellValue, options, rowObject) {
    var dateStr = "";
    if (cellValue) {
        var crtTime = new Date(cellValue);
        dateStr = dateFtt("yyyy-MM-dd hh:mm:ss", crtTime);
    }
    return dateStr;
}

$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sysUserInfo/userInfo/list',
        datatype: "json",
        colModel: [
            {label: 'id', name: 'id', index: 'id', width: 50, key: true, hidden: true},
            {label: '应用标识', name: 'applicationId', index: 'application_id', width: 120},
            {label: '用户名称', name: 'username', index: 'username', width: 80},
            {label: '', name: 'lastModifyTime', index: 'last_modify_time', width: 80, hidden: true},
            {label: '', name: 'password', index: 'password', width: 80, hidden: true},
            {label: '真实姓名', name: 'realname', index: 'realname', width: 80},
            {label: '', name: 'wxUnionId', index: 'wx_union_id', width: 80, hidden: true},
            {label: '驾驶证号码', name: 'drivingdabh', index: 'drivingdabh', width: 80},
            {label: '注册日期', name: 'createDate', index: 'create_date', width: 80, formatter: formatSubscribeTime},
            {label: '身份证号码', name: 'drivingsfzmhm', index: 'drivingsfzmhm', width: 80, hidden: true}
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
    /** 初始日期控件**/
    $("#starttime,#endtime").datetimepicker({
        language: 'zh-CN', //语言设置
        format: 'yyyy-mm-dd hh:ii:ss', //日期格式
        weekStart: 1,  // 默认值：0 ,一周从哪一天开始。0（星期日）到6（星期六）
        autoclose: true, //Boolean. 默认值：false,当选择一个日期之后是否立即关闭此日期时间选择器。
        startView: 2, //Number, String. 默认值：2, 'month',0:小时，1:天，2:月，3:年，4十年
        minView: 0,   //Number, String. 默认值：0, 'hour',日期时间选择器所能够提供的最精确的时间选择视图。
        maxView: 4,    //Number, String. 默认值：4, 'decade' 日期时间选择器最高能展示的选择范围视图。
        todayBtn: true, //默认值: false,显示当天按钮
        todayHighlight: true, //默认值: false ，今日高亮
        minuteStep: 1, //分钟时显示的时间间隔，此处设置为1分钟
        forceParse: false //默认值: true,当选择器关闭的时候，是否强制解析输入框中的值
    });
});

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        q:{
             username: '',
             realname: '',
             drivingdabh: '',
             starttime: '',
             endtime: ''
        },
        user: {}
    },
    computed: {
        createdate: function () {
            var dateStr = "";
            if (this.user && this.user.createDate) {
                var crtTime = new Date(this.user.createDate);
                dateStr = dateFtt("yyyy-MM-dd hh:mm:ss", crtTime);
            } else {
                dateStr = dateFtt("yyyy-MM-dd hh:mm:ss", new Date());
                this.user.createDate = dateStr;
            }
            return dateStr;
        },
        modifyDate: function () {
            console.log(this.user.applicationId);
            var dateStr = '';
            if (this.user && this.user.lastModifyTime) {
                var crtTime = new Date(this.user.createDate);
                dateStr = dateFtt("yyyy-MM-dd hh:mm:ss", crtTime);
            }
            return dateStr;
        }
    },
    methods: {
        query: function () {
            vm.reload();
        },
        reset: function () {
            vm.q.username = '';
            vm.q.realname = '';
            vm.q.drivingdabh = '';
            vm.q.starttime = '';
            vm.q.endtime = '';
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.user = {};
        },
        update: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getInfo(id)
        },
        saveOrUpdate: function (event) {
            var url = vm.user.id == null ? "sysUserInfo/userInfo/save" : "sysUserInfo/userInfo/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.user),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "sysUserInfo/userInfo/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function (id) {
            $.get(baseURL + "sysUserInfo/userInfo/info/" + id, function (r) {
                vm.user = r.user;
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            /*var postData = $("#jqGrid").jqGrid('getGridParam', 'postData');
            $.each(postData, function(k, v){
                delete postData[k];
            });
            var params = {
                "username": $.isEmptyObject($("#username").val()) ? undefined : $("#username").val(),
                "starttime": $.isEmptyObject($("#starttime").val()) ? undefined : $("#starttime").val(),
                "endtime": $.isEmptyObject($("#endtime").val()) ? undefined : $("#endtime").val()
            };*/
            $("#jqGrid").jqGrid('setGridParam', {
                page: page,
                postData: {
                    "username": vm.q.username,
                    "realname": vm.q.realname,
                    "drivingdabh": vm.q.drivingdabh,
                    "starttime": vm.q.starttime,
                    "endtime": vm.q.endtime
                }
            }).trigger("reloadGrid");
        }
    }
});